import os
from datetime import datetime, timedelta
import logging
from logging.handlers import TimedRotatingFileHandler
import re
from w3lib.html import remove_tags
from typing import List


def get_project_base_directory() -> str:
    project_base = os.path.abspath(
        os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            os.pardir
        )
    )
    return project_base


def setup_logging():
    log_dir = os.path.join(get_project_base_directory(), 'logs')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    log_file = os.path.join(log_dir, 'bdmsmcp.log')
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    # 创建一个按时间轮转的日志处理器
    handler = TimedRotatingFileHandler(log_file, when='midnight', interval=1, backupCount=7, encoding="utf-8")
    # 设置日志格式
    formatter = logging.Formatter(
        fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


def get_today_zero_ms():
    # 获取当日0点的时间
    midnight = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    # 转换为时间戳（以秒为单位）
    midnight_timestamp_seconds = midnight.timestamp()
    # 转换为毫秒数
    midnight_timestamp_milliseconds = int(midnight_timestamp_seconds * 1000)
    return str(midnight_timestamp_milliseconds)


def get_today_end_ms():
    # 获取当日0点的时间
    midnight = datetime.now().replace(hour=23, minute=59, second=59, microsecond=999)
    # 转换为时间戳（以秒为单位）
    midnight_timestamp_seconds = midnight.timestamp()
    # 转换为毫秒数
    midnight_timestamp_milliseconds = int(midnight_timestamp_seconds * 1000)
    return str(midnight_timestamp_milliseconds)


def get_before_week_ms():
    current_time = datetime.now()
    future_time = current_time - timedelta(days=7)
    future_time.replace(hour=0, minute=0, second=0, microsecond=0)
    # 转换为时间戳（以秒为单位）
    future_time_timestamp_seconds = future_time.timestamp()
    # 转换为毫秒数
    future_time_timestamp_milliseconds = int(future_time_timestamp_seconds * 1000)
    return str(future_time_timestamp_milliseconds)


def get_after_week_ms():
    current_time = datetime.now()
    future_time = current_time + timedelta(days=7)
    future_time.replace(hour=23, minute=59, second=59, microsecond=999)
    # 转换为时间戳（以秒为单位）
    future_time_timestamp_seconds = future_time.timestamp()
    # 转换为毫秒数
    future_time_timestamp_milliseconds = int(future_time_timestamp_seconds * 1000)
    return str(future_time_timestamp_milliseconds)


def timestamp_format(timestamp: int) -> str:
    seconds = int(timestamp / 1000)
    dt = datetime.fromtimestamp(seconds)
    return dt.strftime("%Y-%m-%d")


def get_temp_images_dir():
    images_dir = os.path.join(get_project_base_directory(), "temp", "images")
    return images_dir


def get_temp_documents_dir():
    documents_dir = os.path.join(get_project_base_directory(), "temp", "documents")
    return documents_dir


def query2keyword(query: str):
    # 使用正则表达式提取关键词
    keywords = re.findall(r'\b\w+\b', query)
    # 去重并排序
    keywords = sorted(set(keywords))
    # 过滤逻辑运算符
    keywords = [word for word in keywords if word not in ['&&', '||', '@', ':']]
    return keywords


def judge_relevant_news(query, title):
    keywords = query2keyword(query)
    for keyword in keywords:
        if re.search(r'\b' + re.escape(keyword) + r'\b', title):
            return True
    return False


def format_milliseconds_to_date(milliseconds: int) -> str:
    # 将毫秒数转换为秒
    seconds = milliseconds / 1000
    # 将秒数转换为日期时间对象
    date_time = datetime.fromtimestamp(seconds)
    # 格式化日期时间对象为字符串
    formatted_date = date_time.strftime("%Y-%m-%d")
    return formatted_date


def clear_scrapy_data(text: str):
    # 替换连续回车为单个回车
    text = remove_tags(text)
    text = re.sub(r'\n', '', text)
    text = text.replace(' ', '')
    return text


def format_news_info(news_info: List):
    print(len(news_info))
    if len(news_info) == 0:
        return "没有找到相关新闻信息。"
    formatted_info = ""
    for item in news_info:
        formatted_info += (
            f"标题：{item['title']}\n"
            f"内容：{clear_scrapy_data(item['content'])}\n"
            f"网站：{item['websiteName']}\n"
            f"发布时间：{format_milliseconds_to_date(int(item['createdAt']))} \n"
        )
    return formatted_info
